import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.marshallers.jackson.JacksonSupport
import akka.stream.ActorMaterializer

import com.zaxxer.hikari.{HikariConfig, HikariDataSource}
import scala.concurrent.{ExecutionContextExecutor, Future}
import java.sql.{Connection, ResultSet}

// 定义单词计数的模型  
case class WordCount(word: String, count: Int)

object WordCountServer extends App with JacksonSupport {

  implicit val system: ActorSystem = ActorSystem("word-count-system")
  implicit val materializer: ActorMaterializer = ActorMaterializer()
  implicit val executionContext: ExecutionContextExecutor = system.dispatcher

  // HikariCP数据库连接池配置  
  val hikariConfig = new HikariConfig()
  hikariConfig.setJdbcUrl("jdbc:mysql://localhost:3306/mysparkcount") // 数据库URL  
  hikariConfig.setUsername("root")  // 数据库用户名
  hikariConfig.setPassword("123")  // 数据库密码
  hikariConfig.setDriverClassName("com.mysql.cj.jdbc.Driver")
  val dataSource = new HikariDataSource(hikariConfig)

  // 查询函数  
  def fetchWordCounts(): Future[List[WordCount]] = Future {
    val connection: Connection = dataSource.getConnection
    try {
      val statement = connection.createStatement()
      val resultSet: ResultSet = statement.executeQuery("SELECT word, count FROM cjy_wordcount")
      Iterator.continually((resultSet, resultSet.next()))
        .takeWhile(_._2)
        .map { case (rs, _) => WordCount(rs.getString("word"), rs.getInt("count")) }
        .toList
    } finally {
      connection.close()
    }
  }

  // 创建HTTP路由  
  val route =
    path("api" / "wordcount") {
      get {
        onComplete(fetchWordCounts()) {
          case scala.util.Success(wordCounts) => complete(wordCounts)
          case scala.util.Failure(ex) => complete(StatusCodes.InternalServerError, ex.getMessage)
        }
      }
    }

  // 启动HTTP服务器  
  val bindingFuture: Future[Http.ServerBinding] = Http().newServerAt("localhost", 8090).bind(route)

  println("路径是"+s"Server online at http://localhost:8090/")
}